class MyResource:

    def query(self):
        print('query database')

    def __enter__(self):
        print('connect resource')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_tb:
            print('process exception')
        else:
            print('no exception')
        print('close resource connection')
        # 返回False时将会在with中抛出异常
        return False


try:
    with MyResource() as resource:
        1 / 0
        resource.query()
except Exception as e:
    print('oh my')
